from aiogram import Router, F
from aiogram.filters import Command, StateFilter
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import StatesGroup, State
from aiogram.types import Message, ReplyKeyboardRemove

from keyboards.set_menu import just_keyboard, cancel_keyboard

from db.PGConnector import PGPurchase, PGFamilyUser
from .utils import try_except_decorator

router = Router()


class BotState(StatesGroup):
    adding_shop = State()
    adding_sum = State()


@router.message(StateFilter(None), F.text == "Покупка")
async def cmd_add(message: Message, state: FSMContext):
    await message.answer(text="🏪 Введите название магазина",
                         reply_markup=cancel_keyboard())
    await state.set_state(BotState.adding_shop)


@try_except_decorator
@router.message(BotState.adding_shop)
async def added_shop(message: Message, state: FSMContext):
    await state.update_data(shop=message.text)
    await message.answer(
        text="💵 Введите сумму",
        reply_markup=cancel_keyboard()
    )
    await state.set_state(BotState.adding_sum)


@try_except_decorator
@router.message(BotState.adding_sum)
async def added_sum(message: Message, state: FSMContext):
    await state.update_data(sum=message.text)
    user_data = await state.get_data()

    user_id = message.chat.id

    purchase_amount, shop_name = user_data['sum'], user_data['shop']

    pg_purchase = PGPurchase()
    purchase_added = pg_purchase.create_purchase(user_id, purchase_amount, shop_name)

    if purchase_added:
        await message.answer(text=f'✅ Покупка добавлена ✅', reply_markup=just_keyboard())
        await state.clear()
    else:
        await message.answer(text='❌ Некорректный формат', reply_markup=cancel_keyboard())
        await message.answer(text='❌ Убедитесь в том, что информация о покупке введена в верном формате.\n\n'
                                  'Пример заполнения:'
                                  '\n🏪 Введите название магазина:\nУнивермаг'
                                  '\n💵 Введите сумму:\n777', reply_markup=cancel_keyboard())